package com.itsci.assignment1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class DeletePatient extends Activity {
	private ListView lv;
	private EditText ed;
	private String path = "/mnt/sdcard/TextFile/Patient.txt";
	private String listview_array[];
	private int textlength = 0;
	private ArrayList<String> array_sort = new ArrayList<String>();
	private int point;
	private ArrayList<String> itemSelect = new ArrayList<String>();
	private String text[];
	private String line;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_patient);
		listview_array = CreateArray();
		lv = (ListView) findViewById(R.id.listView_Patient);
		ed = (EditText) findViewById(R.id.editText_searchPatient);
		lv.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_checked, listview_array));
		lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		registerForContextMenu(lv);
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long id) {
				point = position;
				itemSelect.add(lv.getItemAtPosition(position)+"");
			}
		});

		ed.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				textlength = ed.getText().length();
				array_sort.clear();
				for (int i = 0; i < listview_array.length; i++) {
					if (textlength <= listview_array[i].length()) {
						if (ed.getText()
								.toString()
								.equalsIgnoreCase(
										(String) listview_array[i].subSequence(
												0, textlength))) {
							array_sort.add(listview_array[i]);
						}
					}
				}
				lv.setAdapter(new ArrayAdapter<String>(DeletePatient.this,
						android.R.layout.simple_list_item_checked, array_sort));
				lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}
//
//	@Override
//	public void onCreateContextMenu(ContextMenu menu, View v,
//			ContextMenuInfo menuInfo) {
//		super.onCreateContextMenu(menu, v, menuInfo);
//		if (v.getId() == R.id.listView_Patient) {
//			menu.setHeaderTitle("Menu");
//			SubMenu textMenu1 = menu.addSubMenu("Contact");
//			textMenu1.add(0, 1, 0, "Cal");
//			textMenu1.add(0, 2, 0, "Message");
//			SubMenu textMenu2 = menu.addSubMenu("History");
//			textMenu2.add(1, 3, 0, "Personal History");
//			textMenu2.add(1, 4, 0, "Medical History");
//		}
//	}
//
//	@Override
//	public boolean onContextItemSelected(MenuItem item) {
//		switch (item.getItemId()) {
//		case 1:
//			String uri = "tel:"
//					+ ReadFile(lv.getItemAtPosition(point).toString())[6];
//			Intent intent = new Intent(Intent.ACTION_CALL);
//			intent.setData(Uri.parse(uri));
//			startActivity(intent);
//			break;
//		case 2:
//			String num = ReadFile(lv.getItemAtPosition(point).toString())[6];
//			Intent sendIntent = new Intent(Intent.ACTION_SENDTO,
//					Uri.parse("sms:" + num));
//			startActivity(sendIntent);
//			break;
//		case 3:
//			Intent goPeronalHistory = new Intent(DeletePatient.this,
//					ShowPersonalHistory.class);
//			goPeronalHistory.putExtra("name",
//					ReadFile(lv.getItemAtPosition(point).toString())[0]);
//			startActivity(goPeronalHistory);
//			break;
//		case 4:
//			Intent goMiDicalHistory = new Intent(DeletePatient.this,
//					ShowMidicalHistory.class);
//			startActivity(goMiDicalHistory);
//		default:
//			break;
//		}
//		return super.onContextItemSelected(item);
//	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 0, "Confrim Delete Patient");
		return super.onCreateOptionsMenu(menu);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			line="";
			text = ReadFileForSave();
			int j =0;
			int i=0;
			int length = text.length;
			while(length>0){
				if(text[i].split(",")[0].equalsIgnoreCase(itemSelect.get(j).toString())){
					i++;
					j++;
				}else{
					line += text[i]+"\n";
					i++;
				}
				length--;
				
			}
			
//			for(int i=0;i<text.length;i++){
//				if(text[i].split(",")[0].equalsIgnoreCase(itemSelect.get(j).toString())){
//					j++;
//				}else{
//					line += text[i]+"\n";
//				}
//			}				
			try {

				File file = new File(path);
				if (!file.exists()) {
					try {
						file.createNewFile();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
				FileWriter writer = new FileWriter(file);
				writer.write(line);
				writer.close();
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(DeletePatient.this, "Failed!" + e.getMessage(),
						Toast.LENGTH_LONG).show();

			}
			Intent goPage = new Intent(DeletePatient.this, ShowPatient.class);
			startActivity(goPage);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public String[] CreateArray() {
		ArrayList<String> test = new ArrayList<String>();
		try {
			File myFile = new File(path);
			FileInputStream fIn = new FileInputStream(myFile);
			BufferedReader myReader = new BufferedReader(new InputStreamReader(
					fIn));
			String aDataRow = "";
			while ((aDataRow = myReader.readLine()) != null) {
				String text[] = aDataRow.split(",");
				test.add(text[0]);
			}
			myReader.close();

		} catch (Exception e) {
			Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
					.show();
		}
		return (String[]) test.toArray(new String[test.size()]);
	}
//
//	public String[] ReadFile(String name) {
//		String[] temp = null;
//		try {
//			File myFile = new File(path);
//			FileInputStream fIn = new FileInputStream(myFile);
//			BufferedReader myReader = new BufferedReader(new InputStreamReader(
//					fIn));
//			String aDataRow = "";
//			while ((aDataRow = myReader.readLine()) != null) {
//				String text[] = aDataRow.split(",");
//				if (name.equalsIgnoreCase(text[0])) {
//					temp = aDataRow.split(",");
//				}
//			}
//			myReader.close();
//
//		} catch (Exception e) {
//			Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
//					.show();
//		}
//		return (String[]) temp;
//	}
	
	public String[] ReadFileForSave() {
		ArrayList<String> temp = new ArrayList<String>();
		try {
			File myFile = new File(path);
			FileInputStream fIn = new FileInputStream(myFile);
			BufferedReader myReader = new BufferedReader(new InputStreamReader(
					fIn));
			String aDataRow = "";
			@SuppressWarnings("unused")
			int i=0;
			while ((aDataRow = myReader.readLine()) != null) {
				temp.add(aDataRow);
				i++;
			}
			myReader.close();
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
					.show();
		}
		return (String[]) temp.toArray(new String[temp.size()]);
	}

}